﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace TPA.DataAccess
{
    public class LambdaExpressionHelper
    {
        private static Expression<Func<ProgramDisplayer, bool>> ExpressionBuilder(string propertyName, string constantValue)
        {
            ParameterExpression param = Expression.Parameter(typeof(ProgramDisplayer), "k");
            MemberExpression property = Expression.Property(param, typeof(ProgramDisplayer).GetProperty(propertyName));
            ConstantExpression constValue = Expression.Constant(constantValue, typeof(string));
            MethodCallExpression call = Expression.Call(property, typeof(string).GetMethod("Contains"),
                new ConstantExpression[] { constValue });
            //Expression ET = Expression.Equal(property, constValue);
            Expression<Func<ProgramDisplayer, bool>> exp = Expression.Lambda<Func<ProgramDisplayer, bool>>(call,
                new ParameterExpression[] { param });
            return exp;
        }

        public static Expression<Func<ProgramDisplayer, bool>> ExpressionBuilder(Filter filter)
        {
            var predicate = PredicateBuilder.False<ProgramDisplayer>();
            foreach (string v in filter.Values)
            {
                predicate = predicate.Or(ExpressionBuilder(filter.PropertyName, v));
            }

            return predicate;
        }

        public static Expression<Func<ProgramDisplayer, string>> SelectExpression(string propertyName)
        {
            ParameterExpression param = Expression.Parameter(typeof(ProgramDisplayer), "t");
            MemberExpression property = Expression.Property(param, typeof(ProgramDisplayer).GetProperty(propertyName));
            Expression<Func<ProgramDisplayer, string>> exp = Expression.Lambda<Func<ProgramDisplayer, string>>(property, new ParameterExpression[] { param });
            return exp;
        }
    }
}
